<template>
  <view class="container">
    <!-- 背景遮罩 -->
    <view class="background-mask"></view>
    
    <!-- 进度条 -->
    <view class="progress">
      <text class="progress-text">{{ currentIndex + 1 }}/{{ totalQuestions }}</text>
      <view class="progress-bar">
        <view class="progress-inner" :style="{ width: progressWidth }"></view>
      </view>
    </view>

    <!-- 题目区域 -->
    <view class="question-card">
      <text class="question-text">{{ currentQuestion.text }}</text>
      
      <!-- 选项列表 -->
      <view class="options">
        <view 
          v-for="(option, index) in currentQuestion.options" 
          :key="index"
          class="option-item"
          :class="{
            'correct': showResult && option === currentQuestion.answer,
            'wrong': showResult && selectedAnswer === option && !isCorrect,
            'disabled': showResult
          }"
          @click="selectAnswer(option)"
        >
          <text class="option-letter">{{ String.fromCharCode(65 + index) }}</text>
          <text class="option-text">{{ option }}</text>
        </view>
      </view>

      <!-- 结果反馈 -->
      <view v-if="showResult" class="result-feedback">
        <text class="feedback-text" :class="isCorrect ? 'success' : 'error'">
          {{ isCorrect ? '回答正确！' : '非常遗憾，回答错误' }}
        </text>
        <text class="next-button" @click="nextQuestion">下一题</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      userInfo: null,
      currentIndex: 0,
      totalQuestions: 10, // 固定为10题
      score: 0,
      selectedAnswer: null,
      showResult: false,
      isCorrect: false,
      questions: [], // 初始为空数组
      isLoading: true   // 新增加载状态
    };
  },
  computed: {
    currentQuestion() {
      return this.questions[this.currentIndex];
    },
    progressWidth() {
      return `${((this.currentIndex + 1) / this.totalQuestions) * 100}%`;
    },
  },
  methods: {
    // 获取随机题目
    async fetchQuestions() {
      try {
        uni.showLoading({ title: "题目加载中...", mask: true });
        
        // 调用云函数获取题目
        const res = await uniCloud.callFunction({
          name: "get-questions",
          data: { count: 30 } // 获取30题用于随机筛选
        });

        if (res.result.code === 200) {
          // 随机排序并取前10题
          const shuffled = this.shuffleArray(res.result.data);
          this.questions = shuffled.slice(0, 10);
          this.totalQuestions = this.questions.length;
        } else {
          throw new Error(res.result.msg || "题目获取失败");
        }
      } catch (error) {
        console.error("获取题目失败:", error);
        uni.showToast({
          title: "题目加载失败，请重试",
          icon: "none",
          duration: 2000,
        });
        setTimeout(() => uni.navigateBack(), 2000);
      } finally {
        this.isLoading = false;
        uni.hideLoading();
      }
    },

    // 数组随机排序（Fisher-Yates算法）
    shuffleArray(array) {
      for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
      }
      return array;
    },

    // 选择答案
    selectAnswer(answer) {
      if (this.showResult || this.isLoading) return;

      this.selectedAnswer = answer;
      this.isCorrect = answer === this.currentQuestion.answer;
      this.showResult = true;

      if (this.isCorrect) {
        this.score += 10;
        this.saveScore();
      }
    },

    // 更新用户积分
    async updateUserScore(scoreToAdd) {
      try {
        // const app = getApp();
        // if (!app.globalData.userInfo) {
        //   uni.showToast({ title: "请先登录", icon: "none" });
        //   return;
        // }
        console.log(scoreToAdd)
       const userInfo = uni.getStorageSync("userInfo");
        // 调用云函数更新积分
        const res = await uniCloud.callFunction({
          name: "update-user-score",
          data: {
            userId: userInfo._id,
            score: scoreToAdd,
          },
        });

        if (res.result.code === 200) {
          
          // 更新本地存储
          userInfo.score = userInfo.score +=scoreToAdd
          uni.setStorageSync("userInfo", userInfo);
        } else {
          throw new Error(res.result.msg || "积分更新失败");
        }
      } catch (error) {
        console.error("积分更新失败:", error);
        uni.showToast({
          title: "积分同步失败，请检查网络",
          icon: "none",
        });
        userInfo.score -= scoreToAdd;
        uni.setStorageSync("userInfo", userInfo);
      }
    },

    // 下一题
    nextQuestion() {
      if (this.currentIndex < this.totalQuestions - 1) {
        this.currentIndex++;
        this.resetQuestion();
      } else {
        const today = new Date().toDateString();
        uni.setStorageSync("dailyQuiz", { date: today, answered: true });

        // 更新用户积分
        if (this.score > 0) {
          this.updateUserScore(this.score);
        }

        uni.showModal({
          title: "答题完成",
          content: `本次得分：${this.score}分`,
          showCancel: false,
          success: () => {
            this.resetQuiz();
            uni.navigateBack();
          },
        });
      }
    },

    // 重置题目状态
    resetQuestion() {
      this.selectedAnswer = null;
      this.showResult = false;
      this.isCorrect = false;
    },

    // 重置整个测试
    resetQuiz() {
      this.currentIndex = 0;
      this.score = 0;
      this.resetQuestion();
    },

    // 保存分数
    saveScore() {
      const today = new Date().toDateString();
      const totalScore = uni.getStorageSync("totalScore") || 0;
      uni.setStorageSync("totalScore", totalScore + 10);
      uni.setStorageSync("dailyQuiz", { date: today, answered: true });
    },
  },
  async onLoad() {
    const today = new Date().toDateString();
    const storage = uni.getStorageSync("dailyQuiz") || {};

    // 检查是否已完成当日答题
    if (storage.date === today && storage.answered) {
      uni.showModal({
        title: "提示",
        content: "今日已完成答题",
        showCancel: false,
        success: () => {
          uni.navigateBack();
        },
      });
      return;
    }

    // 获取题目数据
    await this.fetchQuestions();

    // 检查题目有效性
    if (this.questions.length === 0 && !this.isLoading) {
      uni.showToast({ title: "暂无可用题目", icon: "none" });
      setTimeout(() => uni.navigateBack(), 2000);
    }
  },
  onShow() {
    const userInfo = uni.getStorageSync("userInfo");
    this.userInfo = userInfo;
  },
};
</script>

<style scoped>
.container {
  padding: 30rpx;
  min-height: 100vh;
  background-image: url('https://mp-1de2ab47-60cc-4717-bb0c-985e43d6d68e.cdn.bspapp.com/img/explore/answer_bg.png');
  background-size: cover;
  background-position: center;
  position: relative;
}

.background-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 0;
}

.progress {
  margin-bottom: 40rpx;
  position: relative;
  z-index: 1;
}

.progress-text {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 10rpx;
}

.progress-bar {
  height: 10rpx;
  background: #eee;
  border-radius: 5rpx;
  overflow: hidden;
}

.progress-inner {
  height: 100%;
  background: #9A4E26;
  transition: width 0.3s;
}

.question-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
  position: relative;
  z-index: 1;
}

.question-text {
  font-size: 36rpx;
  color: #333;
  line-height: 1.5;
  margin-bottom: 40rpx;
  display: block;
}

.options {
  margin-bottom: 40rpx;
}

.option-item {
  padding: 25rpx;
  border: 2rpx solid #eee;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
  transition: all 0.2s;
  background: rgba(255, 255, 255, 0.9);
}

.option-item:active {
  transform: scale(0.98);
}

.option-letter {
  width: 50rpx;
  height: 50rpx;
  border-radius: 50%;
  background: #f5f5f5;
  text-align: center;
  line-height: 50rpx;
  margin-right: 20rpx;
  font-weight: bold;
  color: #666;
}

.correct {
  border-color: #4CAF50 !important;
  background: #E8F5E9 !important;
}

.wrong {
  border-color: #F44336 !important;
  background: #FFEBEE !important;
}

.disabled {
  opacity: 0.7;
  pointer-events: none;
}

.result-feedback {
  border-top: 1rpx solid #eee;
  padding-top: 30rpx;
  text-align: center;
}

.feedback-text {
  font-size: 32rpx;
  display: block;
  margin-bottom: 30rpx;
}

.success {
  color: #4CAF50;
}

.error {
  color: #F44336;
}

.next-button {
  display: inline-block;
  padding: 15rpx 60rpx;
  background: #9A4E26;
  color: #fff;
  border-radius: 48rpx;
  font-size: 28rpx;
  transition: opacity 0.2s;
}

.next-button:active {
  opacity: 0.8;
}
</style>